package com.letv.core.utils;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.letv.android.sdk.R;
import com.letv.core.bean.AlbumNew;
import com.letv.core.config.LetvConfig;
import com.letv.core.constant.LetvConstant;
import com.letv.core.db.PreferencesManager;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Set;

public class LetvTools {
    /**
     * 5.3开始增加的加密参数方法
     * 
     * @return
     */
    public static String generSignedKey53(HashMap<String, String> maps) {
        if (maps == null || maps.size() == 0) {
            return null;
        }
        StringBuilder builder = new StringBuilder();
        Set<String> set = maps.keySet();
        String[] keyArray = new String[set.size()];
        set.toArray(keyArray);
        Arrays.sort(keyArray);
        for (int i = 0; i < keyArray.length; i++) {
            builder.append(keyArray[i]);
            builder.append("=");
            if (!TextUtils.isEmpty(maps.get(keyArray[i]))) {
                builder.append(maps.get(keyArray[i]));
            }
            builder.append("&");
        }
        builder.append(LetvConstant.MIYUE53);
        return MD5.toMd5(builder.toString());
    }

    /**
     * 生成新版登录接口签名
     * 加密key: e3F5gIfT3zj43MAc3F
     * 加密方法:md5(version . loginname . password . devid . key)，无分隔符(.仅标识字符串连接符)
     * 
     * @return
     */
//    public static String generateLoginSignKey(String loginname, String password) {
//        StringBuilder builder = new StringBuilder();
//        builder.append(LetvUtils.getClientVersionName());
//        builder.append(loginname);
//        builder.append(password);
//        builder.append(LetvConstant.Global.DEVICEID);// 5.3统一修改为Global.DEVICEID,
//                                                     // LetvUtil.getDeviceId(BaseApplication.getInstance()));
//        builder.append("e3F5gIfT3zj43MAc3F");
//        return MD5.toMd5(builder.toString());
//    }

    /**
     * 生成sign的key
     * 
     * @param userid
     * @param pid
     * @return
     */
    public static String generateSignKey(String userid, String pid) {
        StringBuilder builder = new StringBuilder();
        builder.append("mobile");
        builder.append(userid);
        builder.append(pid);
        return MD5.toMd5(builder.toString());
    }

    /**
     * 生成videofile接口的key
     * */
    public static String generateVideoFileKey(String mid, String tm) {
        StringBuilder builder = new StringBuilder();
        builder.append(mid);
        builder.append(",");
        builder.append(tm);
        builder.append(",");
//        builder.append("bh65OzqYYYmHRQ");
        builder.append(LetvConfig.getVideoFileKey());
        return MD5.toMd5(builder.toString());
    }

    /**
     * 批量鉴权加密key
     * 
     * key:bh65O6eus9yRQ
     * 
     * @param mid
     * @param tm
     * @return
     */
    public static String generateBatchAuthorKey(String liveIds, String userId) {
        StringBuilder builder = new StringBuilder();
        builder.append(liveIds);
        builder.append(",");
        builder.append(userId);
        builder.append(",");
        builder.append("bh65O6eus9yRQ");
        return MD5.toMd5(builder.toString());
    }

    /**
     * 生成上传错误日志接口key
     * 
     * @param uuid
     * @return
     */
    public static String generateExceptionFilesKey(String uuid) {
        StringBuilder builder = new StringBuilder();
        builder.append(uuid);
        builder.append("x6e2eAe2sB4ts1289wa2s");
        return MD5.toMd5(builder.toString());
    }

    /**
     * 生成直播加密的key
     * */
    public static String generateLiveEncryptKey(String streamId, String tm) {
        StringBuilder builder = new StringBuilder();
        builder.append(streamId);
        builder.append(",");
        builder.append(tm);
        builder.append(",");
        builder.append(LetvConstant.MIYUE);
        return MD5.toMd5(builder.toString());
    }

    /**
     * 是否有网络
     * */
    // public static boolean hasNet() {
    // NetworkInfo networkInfo = NetworkUtils.getAvailableNetworkInfo();
    //
    // if (networkInfo == null) {
    // return false;
    // }
    // return true;
    // }

    /**
     * 关闭数据库Cursor对象
     */
    public static void closeCursor(Cursor cursor) {
        if (null != cursor) {
            if (!cursor.isClosed()) {
                cursor.close();
            }
        }
    }

    /**
     * 将long型时间（单位：秒）转换为23:12:22形式
     * */
    public static String getNumberTime(long time_second) {

        Formatter formatter = new Formatter(null, Locale.getDefault());

        try {

            long seconds = time_second % 60;

            long minutes = (time_second / 60) % 60;

            long hours = time_second / 3600;

            return formatter.format("%02d:%02d:%02d", hours, minutes, seconds).toString();

        } finally {
            formatter.close();
        }
    }


    /**
     * 得到客户端版本名
     */
//    public static String getClientVersionName() {
//        try {
//            PackageInfo packInfo = BaseApplication.getInstance().getPackageManager()
//                    .getPackageInfo(BaseApplication.getInstance().getPackageName(), 0);
//            return packInfo.versionName;
//        } catch (NameNotFoundException e) {
//            e.printStackTrace();
//        }
//        return "";
//    }

    public static String getClientVersionName(Context context) {
        try {
            PackageInfo packInfo = context.getPackageManager()
                .getPackageInfo(context.getPackageName(), 0);
            return packInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 得到客户端版本号
     */
//    public static int getClientVersionCode() {
//        int verCode = 0;
//        try {
//            PackageInfo packInfo = BaseApplication.getInstance().getPackageManager()
//                    .getPackageInfo(BaseApplication.getInstance().getPackageName(), 0);
//            verCode = packInfo.versionCode;
//        } catch (NameNotFoundException e) {
//            e.printStackTrace();
//            verCode = PreferencesManager.getInstance().getSettingVersionCode();
//        }
//        return verCode;
//    }

    public static int getClientVersionCode(Context context) {
        int verCode = 0;
        try {
            PackageInfo packInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            verCode = packInfo.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            verCode = PreferencesManager.getInstance().getSettingVersionCode();
        }
        return verCode;
    }

    /**
     * 检查是否装在sd卡
     * 
     * @return
     */
    public static boolean sdCardMounted() {
        final String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED) &&
                !state.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
    }

    /**
     * 获取屏幕宽度
     * 
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        return ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();
    }

    /**
     * dip to px 转化
     * 
     * @param mContext
     * @param dipValue
     * @return
     */
    public static int dipToPx(Context mContext, int dipValue) {
        if (null == mContext) {
            return dipValue;
        }

        final float scale = mContext.getResources().getDisplayMetrics().density;
        int pxValue = (int) (dipValue * scale + 0.5f);

        return pxValue;
    }

    /**
     * 判断是否有海外版权
     * */
    public static boolean checkIp(String controlAreas, int disableType) {
        String allowforeign = isAllowforeign(controlAreas, disableType);
        return !AlbumNew.Copyright.NEITHER_P_D.equals(allowforeign);
    }

    public static boolean checkIp(Context context,String controlAreas, int disableType) {
        String allowforeign = isAllowforeign(context,controlAreas, disableType);
        return !AlbumNew.Copyright.NEITHER_P_D.equals(allowforeign);
    }

    /**
     * 判断海外版权
     * */
    public static String isAllowforeign(String controlAreas, int disableType) {
        String allowforeign = AlbumNew.Copyright.ALL_P_D;
        /**
         * 0-有播放和下载版权 3-无播放和下载版权
         * 
         * controlAreas string 受控区域，多个逗号分隔，结合disableType字段处理，空为全部允许 disableType
         * string 1:全部允许;2:部分允许;3:全部屏蔽;4:部分屏蔽
         */
        if (TextUtils.isEmpty(controlAreas)) {
            return allowforeign;
        }
        switch (disableType) {
            case 1:
                allowforeign = AlbumNew.Copyright.ALL_P_D;
                break;
            case 2:
                if (LetvSDKUtils.getIp() != null) {
                    if (LetvSDKUtils.getIp().getUserCountry() != null) {
                        if (controlAreas.contains(LetvSDKUtils.getIp().getUserCountry())) {
                            allowforeign = AlbumNew.Copyright.ALL_P_D;
                        } else {
                            allowforeign = AlbumNew.Copyright.NEITHER_P_D;
                        }
                    } else {
                        allowforeign = AlbumNew.Copyright.ALL_P_D;
                    }
                } else {
                    allowforeign = AlbumNew.Copyright.ALL_P_D;
                }
                break;
            case 3:
                allowforeign = AlbumNew.Copyright.NEITHER_P_D;
                break;
            case 4:
                if (LetvSDKUtils.getIp() != null) {
                    if (controlAreas.contains(LetvSDKUtils.getIp().getUserCountry())) {
                        allowforeign = AlbumNew.Copyright.NEITHER_P_D;
                    } else {
                        allowforeign = AlbumNew.Copyright.ALL_P_D;
                    }
                } else {
                    allowforeign = AlbumNew.Copyright.ALL_P_D;
                }
                break;
        }
        return allowforeign;
    }

    public static String isAllowforeign(Context context,String controlAreas, int disableType) {
        String allowforeign = AlbumNew.Copyright.ALL_P_D;
        /**
         * 0-有播放和下载版权 3-无播放和下载版权
         *
         * controlAreas string 受控区域，多个逗号分隔，结合disableType字段处理，空为全部允许 disableType
         * string 1:全部允许;2:部分允许;3:全部屏蔽;4:部分屏蔽
         */
        if (TextUtils.isEmpty(controlAreas)) {
            return allowforeign;
        }
        switch (disableType) {
            case 1:
                allowforeign = AlbumNew.Copyright.ALL_P_D;
                break;
            case 2:
                if (LetvSDKUtils.getIp() != null) {
                    if (LetvSDKUtils.getIp().getUserCountry() != null) {
                        if (controlAreas.contains(LetvSDKUtils.getIp().getUserCountry())) {
                            allowforeign = AlbumNew.Copyright.ALL_P_D;
                        } else {
                            allowforeign = AlbumNew.Copyright.NEITHER_P_D;
                        }
                    } else {
                        allowforeign = AlbumNew.Copyright.ALL_P_D;
                    }
                } else {
                    allowforeign = AlbumNew.Copyright.ALL_P_D;
                }
                break;
            case 3:
                allowforeign = AlbumNew.Copyright.NEITHER_P_D;
                break;
            case 4:
                if (LetvSDKUtils.getIp() != null) {
                    if (controlAreas.contains(LetvSDKUtils.getIp().getUserCountry())) {
                        allowforeign = AlbumNew.Copyright.NEITHER_P_D;
                    } else {
                        allowforeign = AlbumNew.Copyright.ALL_P_D;
                    }
                } else {
                    allowforeign = AlbumNew.Copyright.ALL_P_D;
                }
                break;
        }
        return allowforeign;
    }

//    public static String getTextFromServer(String constantId, String defaultText) {
//        String result = "";
//        result = TipUtils.getTipMessage(constantId);
//        if (TextUtils.isEmpty(result))
//            result = defaultText;
//        return result;
//    }

    public static String getTextFromServer(Context context,String constantId, String defaultText) {
        String result = "";
        result = TipUtils.getTipMessage(context,constantId);
        if (TextUtils.isEmpty(result))
            result = defaultText;
        return result;
    }

//    public static String getTextTitleFromServer(String constantId, String defaultText) {
//        String result = "";
//        result = TipUtils.getTipTitle(constantId);
//        if (TextUtils.isEmpty(result)) {
//            result = defaultText;
//        }
//        return result;
//    }

    public static String getTextTitleFromServer(Context context,String constantId, String defaultText) {
        String result = "";
        result = TipUtils.getTipTitle(context,constantId);
        if (TextUtils.isEmpty(result)) {
            result = defaultText;
        }
        return result;
    }

    public static class PointsUtils {
        public static boolean canLoginGainPoints() {
            if (!PreferencesManager.getInstance().isLogin()) {
                return false;
            }
            String date = PreferencesManager.getInstance().getUserId()
                    + StringUtils.timeString(System.currentTimeMillis());
            String savedDate = PreferencesManager.getInstance().getPointsLoginGainDate();
            return !savedDate.equals(date);
        }

        public static boolean canVideoGainPoints(String date) {
            String savedDate = PreferencesManager.getInstance().getPointsVideoGainDate();
            return !savedDate.equals(date);
        }

        public static boolean canShareGainPoints() {
            if (!PreferencesManager.getInstance().isLogin()) {
                return false;
            }
            String date = PreferencesManager.getInstance().getUserId()
                    + StringUtils.timeString(System.currentTimeMillis());
            String savedDate = PreferencesManager.getInstance().getPointsShareGainDate();
            return !savedDate.equals(date);
        }

        public static void saveLoginGainPoints() {
            String date = PreferencesManager.getInstance().getUserId()
                    + StringUtils.timeString(System.currentTimeMillis());
            PreferencesManager.getInstance().setPointsLoginGainDate(date);
        }

        public static void saveVideoGainPoints(String date) {
            PreferencesManager.getInstance().setPointsVideoGainDate(date);
        }

        public static void saveSharePoints() {
            String date = PreferencesManager.getInstance().getUserId()
                    + StringUtils.timeString(System.currentTimeMillis());
            PreferencesManager.getInstance().setPointsShareGainDate(date);
        }
    }

    /**
     * 拷贝集合
     * 
     * @param <T>
     * @return
     */
//    public static <T, P> ArrayList<T> copyBeanList(List<P> list, Class<T> clazz) {
//        if (list == null)
//            return null;
//        ArrayList<T> copyList = new ArrayList<T>();
//        for (int i = 0; i < list.size(); i++) {
//            P p = list.get(i);
//            T t = copyBean(p, clazz);
//            copyList.add(t);
//        }
//        return copyList;
//    }

    /**
     * 拷贝对象
     * 
     * @param <T>
     * @param <T>
     * @param object
     * @return
     */
//    public static <T, P> T copyBean(P p, Class<T> clazz) {
//        if (p == null)
//            return null;
//        T t = null;
//        try {
//            t = clazz.newInstance();
//        } catch (Exception e1) {
//            // do nothind
//            e1.printStackTrace();
//        }
//        Field[] fields = null;
//        try {
//            fields = p.getClass().getDeclaredFields();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        for (int i = 0; i < fields.length; i++) {
//            try {
//                fields[i].setAccessible(true);
//                String fieldName = fields[i].getName();
//                Object fieldValue = fields[i].get(p);
//                try {
//                    Field filed = clazz.getDeclaredField(fieldName);
//                    filed.setAccessible(true);
//                    filed.set(t, fieldValue);
//                } catch (Exception e) {
//
//                    e.printStackTrace();
//                }
//            } catch (Exception e) {
//
//                e.printStackTrace();
//            }
//        }
//        return t;
//    }

    public static void logBook(String log, Class<?> c) {
        if (!LetvConfig.isDebug()) {
            return;
        }
        LogInfo.log("book", c.getSimpleName() + " " + log);
    }

    public static boolean checkServiceIsRunning(Context context, String serviceName) {
        boolean isServiceRunning = false;
        if (context == null || TextUtils.isEmpty(serviceName)) {
            return false;
        }
        // 检查Service状态
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (manager == null) {
            return false;
        }

        List<RunningServiceInfo> list = manager.getRunningServices(Integer.MAX_VALUE);
        if (BaseTypeUtils.isListEmpty(list)) {
            return false;
        }

        for (ActivityManager.RunningServiceInfo service : list) {
            if (service != null && service.service != null && serviceName.equals(service.service.getClassName())) {
                isServiceRunning = true;
                break;
            }
        }
        return isServiceRunning;
    }

    public static String calculateDownloadSpeed(long lastStarted, long curtime, long downloadedSize) {
        long time = (curtime - lastStarted) / 1000;
        if (time > 0) {
            long bps = downloadedSize / time;
            return ("" + bps / 1024);
        } else {
            return "";
        }
    }

    /*
     * input parameter: 当前下载速度，单位：KB
     */
    public static String formatSpeed(long speed) {
        if (speed < 1) {
            return ""; // ----0KB/s默认为不显示，产品要求
        }
        if (speed >= 1024 && speed < 1024 * 1024) {
            float msd = (float) speed / 1024;
            return String.format("%.1f", msd) + "M/s";
        }
        if (speed > 1024 * 1024) {
            float gsd = (float) speed / 1024;
            return String.format("%.1f", gsd) + "G/s";
        }
        return speed + "K/s";
    }

    /**
     * yyyy-MM-dd HH:mm:ss转换为million
     * 
     * @param time yyyy-MM-dd HH:mm:ss格式
     * @return
     */
    public static long formTimeToMillion(String time) {
        try {
            DateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dt = sd.parse(time);
            return dt.getTime();
        } catch (ParseException e) {
        }
        return 0;
    }

    /**
     * 格式为时间字符串为昨天、今天、明天
     * 
     * @param context
     * @param time yyyy-MM-dd HH:mm:ss格式
     * @return
     */
    public static String formTimeToDay(Context context, String time) {
        Calendar today = Calendar.getInstance();
        Calendar other = Calendar.getInstance();

        DateFormat df_date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat df_time = new SimpleDateFormat("HH:mm");
        try {
            Date other_date = df_date.parse(time);
            String tm = " " + df_time.format(other_date);
            today.setTime(new Date());
            today.set(Calendar.HOUR_OF_DAY, 0);
            today.set(Calendar.MINUTE, 0);
            today.set(Calendar.SECOND, 0);
            other.setTime(other_date);
            float intervalMilli = (float) (other.getTimeInMillis() - today.getTimeInMillis()) / (24 * 60 * 60 * 1000);
            int xcts = (int) Math.floor(intervalMilli);
            switch (xcts) {
                case 0:

                    return context.getString(R.string.letvutil_week_tody) + tm;
                case 1:
                    return context.getString(R.string.letvutil_week_tomorrow) + tm;
                    // case 2:
                    // return context.getString(R.string.letvutil_week_after_tomorrow)+tm;
                case -1:
                    return context.getString(R.string.letvutil_week_yesterday) + tm;
                    // case -2:
                    // return context.getString(R.string.letvutil_week_before_yesterday)+tm;
            }
            // int intervalYear = other.get(Calendar.YEAR) - today.get(Calendar.YEAR);
            // DateFormat df_day;
            // if(intervalYear == 0){
            // df_day = new SimpleDateFormat("MM-dd HH:mm");
            // }else if(intervalYear == 1){
            // df_day = new SimpleDateFormat("明年 MM-dd HH:mm");
            // }else if(intervalYear == -1){
            // df_day = new SimpleDateFormat("去年  MM-dd HH:mm");
            // }else{
            // df_day = new SimpleDateFormat("yyyy MM-dd HH:mm");
            // }

            DateFormat df_day = new SimpleDateFormat("MM月dd日 HH:mm");

            return df_day.format(df_date.parse(time));
        } catch (ParseException e) {
        }
        return time;
    }

    /**
     * 改变图片的亮度
     * 
     * @param imageView 图片组件
     * @param brightness 亮度值
     */
    public static void changeLight(View imageView, int brightness) {
        ColorMatrix cMatrix = new ColorMatrix();
        cMatrix.set(new float[] { 1, 0, 0, 0, brightness, 0, 1, 0, 0, brightness,// 改变亮度
                0, 0, 1, 0, brightness, 0, 0, 0, 1, 0 });
        ((ImageView) imageView).setColorFilter(new ColorMatrixColorFilter(cMatrix));
    }

    /**
     * 评论点赞数业务逻辑
     * 预期结果：1）<10000，直接显示数字
     * 2）>=10000,显示X.X万，1.0万显示1万
     * 3）>=1亿，显示X.X亿
     */

    public static String toCommentLikeCountText(int playCount) {
        if (playCount <= 0) {
            return "";
        } else if (playCount < 10000) {
            DecimalFormat df = new DecimalFormat("#,###");
            String m = df.format(playCount);
            return m + "";
        } else if (playCount <= 100000000) {
            double count = playCount / 10000.0;
            DecimalFormat df = new DecimalFormat("#,###.0");
            String m = df.format(count);
            if (m != null && m.endsWith(".0")) {
                m = m.substring(0, m.length() - 2);
            }
            return m + "万";
        } else {// 亿次以上
            double count = playCount / 100000000.0;
            DecimalFormat df = new DecimalFormat("#,###.0");
            String m = df.format(count);
            if (m != null && m.endsWith(".0")) {
                m = m.substring(0, m.length() - 2);
            }
            return m + "亿";
        }
    }
}
